package wnhz.com.business.shareshop.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.base.MyBaseFragment;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.shareshop.activity.home.ConfirmOrderActivityS;
import wnhz.com.business.shareshop.activity.home.RebateGoodsDetailsActivityS;
import wnhz.com.business.shareshop.bean.ShoppingCartListBean;
import wnhz.com.business.shareshop.ui.StoreActivityS;
import wnhz.com.business.uitls.CommonUtils;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * 购物车:(共享商城的)
 */

public class ShoppingCartFragment extends MyBaseFragment implements ActionBarClickListener, View.OnClickListener {
    private MyBaseActivity activity;

    @BindView(R.id.actionbar) //顶部标题
    TranslucentActionBar actionbar;

    @BindView(R.id.rv_shoppingcart_goods) //购物车物品ID
    RecyclerView rvShoppingcartGoods;

    @BindView(R.id.tv_txt)
    TextView tvTxt;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_makepay)
    TextView tvMakepay; //确认支付
    @BindView(R.id.img_quanxuan)
    ImageView img_quanxuan;//全选按钮
    @BindView(R.id.empty_layout)
    LinearLayout empty_layout;
    @BindView(R.id.tv_msg)
    TextView tv_msg;


    private List<ShoppingCartListBean.InfoBean> itemdata = new ArrayList<>();
    private Boolean isEdit = false;

    private BaseRVAdapter adapter;

    @Override
    protected void handleMsg(Message msg) {

    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_shopping_trolley, container, false);
        ButterKnife.bind(this, view);
        activity = (MyBaseActivity) getActivity();
        actionbar.setData("购物车", 0, null, 0, "编辑", 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        initview();
        loadData();
        return view;
    }

    private void loadData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        itemdata.clear();
        XUtil.Post(Url.CART_CARTLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("----------------", "---------------" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    if (re.equals("1")) {
                        Gson gson = new Gson();
                        ShoppingCartListBean shoppingCartListBean = gson.fromJson(result, ShoppingCartListBean.class);
                        itemdata = shoppingCartListBean.getInfo();
                    }else if (re.equals("-1")){
                        activity.MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        activity.MyToast(jsonObject.optString("info"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                if (itemdata != null&&itemdata.size()>0) {
                    empty_layout.setVisibility(View.GONE);
                    rvShoppingcartGoods.setVisibility(View.VISIBLE);
                    initdatabuys();
                    upCheckedStates();//更新选中状态
                }else {
                    empty_layout.setVisibility(View.VISIBLE);
                    rvShoppingcartGoods.setVisibility(View.GONE);
                    tv_msg.setText("购物车竟然是空的");
                    upCheckedStates();//更新选中状态
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void initview() {
        rvShoppingcartGoods.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        tvMakepay.setOnClickListener(this);
    }
    private void initdatabuys() {
        adapter=new BaseRVAdapter(getContext(), itemdata) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_shopcar;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position1) {
                Glide.with(activity).load(itemdata.get(position1).getStore_info().getLogo()).error(R.mipmap.ic_launcher).into(holder.getImageView(R.id.img_store));
                holder.setTextView(R.id.tv_shopname,itemdata.get(position1).getStore_info().getName());
                holder.setImageResource(R.id.cb_checkstore,itemdata.get(position1).isStoreCheck()?R.drawable.ic_home_selected:R.drawable.ic_home_unselected);
                final List<ShoppingCartListBean.InfoBean.GoodsBean> goods = itemdata.get(position1).getGoods();
                holder.getView(R.id.cb_checkstore).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        itemdata.get(position1).setStoreCheck(!itemdata.get(position1).isStoreCheck());
                        List<ShoppingCartListBean.InfoBean.GoodsBean> goodsBeanList = itemdata.get(position1).getGoods();
                        for (int i = 0; i < goodsBeanList.size(); i++) {
                            goodsBeanList.get(i).setGoodsCheck(itemdata.get(position1).isStoreCheck());
                        }
                        notifyDataSetChanged();
                        upCheckedStates();//更新选中状态
                    }
                });

                holder.getTextView(R.id.tv_shopname).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//跳转到店铺
                        startActivity(StoreActivityS.createIntent(activity,itemdata.get(position1).getStore_info().getStore_id()));
                    }
                });

                RecyclerView recyclerView=holder.getView(R.id.recycler_inner);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
                recyclerView.setAdapter(new BaseRVAdapter(getContext(), goods) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_shoppingcart_goods;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, final int position) {
                        if (isEdit){
                            holder.getView(R.id.ll_edit).setVisibility(View.VISIBLE);
                            holder.getTextView(R.id.sku_num).setVisibility(View.GONE);
                        }else {
                            holder.getView(R.id.ll_edit).setVisibility(View.INVISIBLE);
                            holder.getTextView(R.id.sku_num).setVisibility(View.VISIBLE);
                        }
                        if (goods.get(position).isGoodsCheck()) {
                            holder.setImageResource(R.id.iv_choses, R.drawable.ic_home_selected);
                        } else {
                            holder.setImageResource(R.id.iv_choses, R.drawable.ic_home_unselected);
                        }

                        Glide.with(getActivity()).load(goods.get(position).getLogo_pic()).error(R.mipmap.ic_launcher).into(holder.getImageView(R.id.iv_icon));
                        holder.setTextView(R.id.tv_name, goods.get(position).getGoods_name());
                        holder.setTextView(R.id.tv_newprice, "押金 ¥ " + goods.get(position).getPrice());
                        holder.setTextView(R.id.tv_num, goods.get(position).getNum());
                        holder.getView(R.id.iv_choses).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                goods.get(position).setGoodsCheck(!goods.get(position).isGoodsCheck());
                                upCheckedStates();//更新选中状态
                                boolean isStoreCheck=true;
                                for (int i = 0; i < goods.size(); i++) {
                                    if (!goods.get(i).isGoodsCheck()){
                                        isStoreCheck=false;
                                    }
                                }
                                itemdata.get(position1).setStoreCheck(isStoreCheck);
                                adapter.notifyDataSetChanged();
                            }
                        });
                        holder.getView(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                goodsAdd(goods.get(position).getCartid(),"1");
                            }
                        });
                        holder.getView(R.id.iv_jian).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                goodsAdd(goods.get(position).getCartid(),"2");
                            }
                        });
                        if (TextUtils.isEmpty(goods.get(position).getSkuinfo())) {
                            holder.getView(R.id.tv_sku).setVisibility(View.INVISIBLE);
                        } else {
                            holder.getView(R.id.tv_sku).setVisibility(View.VISIBLE);
                            holder.setTextView(R.id.tv_sku, goods.get(position).getSkuinfo());
                            holder.setTextView(R.id.sku_num,"X " + goods.get(position).getNum());
                        }


                        holder.getView(R.id.ll_items).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(RebateGoodsDetailsActivityS.createIntent(activity, goods.get(position).getGoods_id(), goods.get(position).getLogo_pic(), "4"));
                            }
                        });
                    }

                });
            }
        };
        rvShoppingcartGoods.setAdapter(adapter);
    }
    String carIds ="";
    boolean isAllChecked=false;
    private int chooseStoreNum = 0;//已选中商品的个数
    private double totalMoney = 0.00;//总价
    private void upCheckedStates(){
        carIds ="";
        isAllChecked =true;
        chooseStoreNum =0;
        totalMoney =0.00;
        for (int i = 0; i < itemdata.size(); i++) {
            List<ShoppingCartListBean.InfoBean.GoodsBean> goods = itemdata.get(i).getGoods();
            for (int j = 0; j < goods.size(); j++) {
                if (goods.get(j).isGoodsCheck()){
                    carIds +="-"+goods.get(j).getCartid();
                    if (!TextUtils.isEmpty(goods.get(j).getPrice())&&!TextUtils.isEmpty(goods.get(j).getNum())){
                        totalMoney+=Double.parseDouble(goods.get(j).getPrice())*Integer.parseInt(goods.get(j).getNum());
                    }
                    chooseStoreNum++;
                }else {
                    isAllChecked=false;
                }
            }
        }
        tvNumber.setText(isEdit?chooseStoreNum+"个":"¥"+ CommonUtils.doubleToString(totalMoney));
        img_quanxuan.setImageResource(isAllChecked?R.drawable.ic_home_selected:R.drawable.ic_home_unselected);
    }


    @OnClick({R.id.img_quanxuan,R.id.tv_quanxuan})
    public void setImgAllChoose(){
        isAllChecked=!isAllChecked;
        if (img_quanxuan != null) {
            for (int i = 0; i < itemdata.size(); i++) {
                itemdata.get(i).setStoreCheck(isAllChecked);
                List<ShoppingCartListBean.InfoBean.GoodsBean> goods = itemdata.get(i).getGoods();
                for (int j = 0; j < goods.size(); j++) {
                    goods.get(j).setGoodsCheck(isAllChecked);
                }
            }
            if (null != adapter) {
                adapter.notifyDataSetChanged();
            }
            upCheckedStates();
        }

    }

    @Override
    public void onLeftClick() {

    }

    @Override
    public void onRightClick() {
        isEdit=!isEdit;
        if (isEdit) {
            initdatabuys();
            tvTxt.setText("已选");
            actionbar.setRight("完成");
            tvMakepay.setText("删除");
            tvNumber.setText(chooseStoreNum + "个");

        } else {
            tvTxt.setText("合计");
            actionbar.setRight("编辑");
            tvMakepay.setText("确认支付");
            tvNumber.setText("¥ " + CommonUtils.doubleToString(totalMoney));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_makepay:
                if (isEdit){//删除
                    if (TextUtils.isEmpty(carIds)){
                        activity.MyToast("请选择商品");
                    }else {
                        deleteGoods(carIds+"-");
                    }
                }else {//结算
                    if (TextUtils.isEmpty(carIds)){
                        activity.MyToast("请选择商品");
                    }else {
                        startActivity(ConfirmOrderActivityS.createIntent(activity, carIds+"-"));
                    }
                }
                break;
        }
    }

    private void deleteGoods(String carIds) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("cartID", carIds);
        /**
         * 删除购物车中的商品
         @param str token
         @param str cartID    -1-2-3-
         */
        activity.showDialog("加载中");
        XUtil.Post(Url.CART_DELCART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("----------------", "---------------" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    activity.MyToast(jsonObject.optString("info"));
                    if (re.equals("1")) {
                        loadData();
                        adapter.notifyDataSetChanged();
                    }else if ("-1".equals(re)){
                        activity.MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        activity.MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                activity.closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
            }
        });
    }
    private void goodsAdd(final String cartid, final String set_type) {

        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getToken());
        map.put("cart_id", cartid);
        map.put("set_type", set_type);
        /**
         * 修改购物车
         * @param str token
         * @param int cart_id   购物车id
         * @param int set_type 	1-加 2-减
         */
        activity.showDialog("加载中");
        XUtil.Post(Url.CART_SETCART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("----------------", "---------------" + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("re");
                    activity.MyToast(jsonObject.optString("info"));
                    if (re.equals("1")) {
//                        loadData();

                        if (set_type.equals("1")){//添加
                            for (int i = 0; i < itemdata.size() ; i++) {
                                for (int j = 0;j < itemdata.get(i).getGoods().size(); j++) {
                                    if (itemdata.get(i).getGoods().get(j).getCartid() == cartid){
                                        itemdata.get(i).getGoods().get(j).setNum("" + ( Integer.valueOf(itemdata.get(i).getGoods().get(j).getNum()) + 1));
                                        adapter.notifyDataSetChanged();
                                        upCheckedStates();
                                    }
                                }
                            }
                        }else if (set_type.equals("2")){//减去
                            for (int i = 0; i < itemdata.size() ; i++) {
                                for (int j = 0;j < itemdata.get(i).getGoods().size(); j++) {
                                    if (itemdata.get(i).getGoods().get(j).getCartid() == cartid) {
                                        itemdata.get(i).getGoods().get(j).setNum("" + (Integer.valueOf(itemdata.get(i).getGoods().get(j).getNum()) - 1));
                                        adapter.notifyDataSetChanged();
                                        upCheckedStates();
                                    }
                                }
                            }
                        }

                    }else if (re.equals("-1")){
                        activity.MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        activity.MyToast(jsonObject.optString("info"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                activity.closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
            }
        });
    }

}
